package Map_Study.HashMap_01;

import java.util.HashMap;
import java.util.Objects;

public class HashMapDemo1 {
    public static void main(String[] args) {
        /*
            创建一个HashMap集合，键是Student对象，值是籍贯（String）
            存储三个键值对对象，并遍历
            需求，同姓名，同年龄认为是同一个学生

            核心点：
                HashMap的键位置如果存储的是自定义对象，则需要在对象里重写hashCode和equals方法
         */
        HashMap<Student, String> map = new HashMap<>();
        map.put(new Student("zhangsan",23), "北京");
        map.put(new Student("lisi",24), "上海");
        map.put(new Student("wangwu",25), "广东");

        //遍历集合
        map.forEach((key,value)-> System.out.println(key + " " + value));

    }
}

class Student {
    private String name;
    private int age;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return age == student.age && Objects.equals(name, student.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }

    public Student() {
    }

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    /**
     * 获取
     * @return name
     */
    public String getName() {
        return name;
    }

    /**
     * 设置
     * @param name
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * 获取
     * @return age
     */
    public int getAge() {
        return age;
    }

    /**
     * 设置
     * @param age
     */
    public void setAge(int age) {
        this.age = age;
    }

    public String toString() {
        return "Cat{name = " + name + ", age = " + age + "}";
    }
}
